<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      @submit.native.prevent
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入说明"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div :class="tableMain" v-show="tableMainShow">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            :disabled="this.mainids.length != 1"
            >新增</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            :disabled="this.mainids.length != 1"
            @click="handleAddCode"
            >新增编码器</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd('super')"
            >新增超类</el-button
          >
        </el-col>
        <el-col :span="1.5" style="float: right">
          <el-button
            size="mini"
            @click="tableExtend(1)"
            icon="el-icon-full-screen"
          ></el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="typeList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleMainSelectionChange"
        stripe
        :header-cell-style="{ background: '#F6F8FB' }"
        @row-click="(row) => checkAttr(row.id, row.name)"
        :height="maxHeight"
        v-scrollbar="'.el-table__body-wrapper'"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="名称"
          prop="name"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="ID"
          prop="id"
        />
        <el-table-column
          label="说明"
          align="center"
          prop="description"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="系统名称"
          align="center"
          prop="systemName"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column label="ID" align="center" prop="id"/> -->
        <!-- <el-table-column label="父ID" align="center" prop="parentid"/> -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <!-- <el-dropdown>
              <span class="el-dropdown-link">
                操作选择<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['pms:type:edit']"
                  >修改</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['pms:type:remove']"
                  >删除</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="checkAttr(scope.row.id,scope.row.name)"
                    v-hasPermi="['pms:type:edit']"
                  >查看属性</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
            <div class="operate-group">
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-edit"
                :plain="false"
                @click="handleUpdate(scope.row)"
                >编辑</span
              >
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-delete"
                :plain="false"
                @click="handleDelete(scope.row)"
                >删除</span
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <resize-bar/>
    <div :class="tableDepend" v-show="tableDependShow">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addAttr"
            >新增属性
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="updateSheet"
            >更新数据表
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="produceCode"
            >生成代码
          </el-button>
        </el-col>
        <el-col :span="1.5" style="float: right">
          <el-button
            size="mini"
            @click="tableExtend(2)"
            icon="el-icon-full-screen"
          ></el-button>
        </el-col>
        <div class="tableDependTitle">{{ tableDependName }} 的属性</div>
      </el-row>
      <el-table
        v-loading="loading"
        :data="attrList"
        stripe
        @selection-change="handleDependSelectionChange"
        :header-cell-style="{ background: '#F6F8FB' }"
        :height="maxHeight"
        v-scrollbar="'.el-table__body-wrapper'"
      >
        <el-table-column label="名称" align="center" prop="columnName" />
        <el-table-column
          label="描述"
          align="center"
          prop="columnComment"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="类型" align="center" prop="columnType" />
        <el-table-column
          label="状态"
          align="center"
          prop="status"
          :formatter="statusFormat"
        />
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-button-->
        <!--              size="mini"-->
        <!--              type="text"-->
        <!--              icon="el-icon-delete"-->
        <!--              @click="attrDelete(scope.row.id)"-->
        <!--            >移除</el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <pagination
        v-show="attrTotal > 0"
        :total="attrTotal"
        :page.sync="queryAttrParams.pageNum"
        :limit.sync="queryAttrParams.pageSize"
        @pagination="getAttrList"
      />
    </div>

    <!-- 添加或修改分类管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-if="open"
      width="500px"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="父类" prop="parentid" v-if="form.parentid != 0">
          <el-select v-model="form.parentid" disabled>
            <el-option
              v-for="dict in selectTypeList"
              :key="dict.id"
              :label="dict.description"
              :value="dict.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属模块" prop="moduleName">
          <el-select v-model="form.moduleName">
            <el-option
              v-for="dict in sysModule"
              :key="dict.id"
              :label="dict.description"
              :value="dict.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="form.systemName" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改分类属性对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="attrOpen"
      v-if="attrOpen"
      width="500px"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        ref="attrForm"
        :model="attrForm"
        :rules="attrRules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="名称" prop="columnName">
          <el-input v-model="attrForm.columnName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="column_comment">
          <el-input v-model="attrForm.columnComment" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="类型" prop="columnType">
          <el-input v-model="attrForm.columnType" placeholder="请输入类型" />
        </el-form-item>
        <el-form-item label="长度" prop="columnLength">
          <el-input v-model="attrForm.columnLength" placeholder="请输入长度" />
        </el-form-item>
        <el-form-item label="默认值" prop="defaultVal">
          <el-input v-model="attrForm.defaultVal" placeholder="请输入默认值" />
        </el-form-item>
        <el-form-item label="JAVA类型" prop="javaType">
          <el-input v-model="attrForm.javaType" placeholder="请输入JAVA类型" />
        </el-form-item>
        <el-form-item label="JAVA字段" prop="javaField">
          <el-input
            v-model="attrForm.javaField"
            placeholder="请输入JAVA字段名"
          />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否主键">
              <el-switch v-model="attrForm.isPk"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否自增">
              <el-switch v-model="attrForm.isIncrement"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否必填">
              <el-switch v-model="attrForm.isRequired"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAttrForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增编码器 -->
    <el-dialog
      title="新增编码器"
      :visible.sync="codeOpen"
      v-if="codeOpen"
      width="500px"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        ref="codeForm"
        :model="codeForm"
        :rules="codeRules"
        label-width="100px"
        @submit.native.prevent
      >
        <el-form-item label="编码前缀" prop="codePrefix" required>
          <el-input v-model="codeForm.codePrefix" placeholder="请输入前缀" />
        </el-form-item>
        <el-form-item label="编码当前值" prop="currentValue" required>
          <el-input
            v-model="codeForm.currentValue"
            placeholder="请输入当前值"
          />
        </el-form-item>
        <el-form-item label="编码" prop="codeNumberLength" required>
          <el-input
            v-model="codeForm.codeNumberLength"
            placeholder="请输入位长"
            type="number"
          />
        </el-form-item>
        <el-form-item label="编码后缀" prop="codeSuffix">
          <el-input v-model="codeForm.codeSuffix" placeholder="请输入后缀" />
        </el-form-item>
        <el-form-item label="编码器描述" prop="description">
          <el-input v-model="codeForm.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCodeForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType,
  listAttr,
  delAttr,
  updateAttr,
  addAttrForm,
  updateSheet,
  produceCode,
} from "@/api/pms/type";
import { addData } from "@/api/dynamic/dynamic";
import dynamicTreeTable from "@/views/components/dynamicTreeTable";
import { deepClone } from "@/utils";

export default {
  inject: ["app"],
  name: "Type",
  components: {
    resizeBar: () => import("@/views/components/resizeBar"),
    dynamicTreeTable,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      mainids: [],
      dependids: [],
      mainselected: [],
      dependselected: [],
      // 总条数
      total: 0,
      attrTotal: 0,
      tableMain: "table-main",
      tableDepend: "table-depend",
      tableMainShow: true,
      tableDependShow: true,
      tableMainOperates: {
        // 列操作按钮
        width: 150,
        list: [
          {
            description: "修改",
            name: "修改",
            status: "1",
            type: "1",
            hasPermi: ["pms:type:remove"],
          },
          {
            description: "删除",
            name: "删除",
            status: "1",
            type: "1",
            hasPermi: ["pms:type:remove"],
          },
        ],
      },
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: true, // 是否支持列表项选中功能
      },
      flag: true,
      // 分类管理表格数据
      typeList: [],
      attrList: [],
      // 弹出层标题
      title: "",
      typeID: "",
      tableDependName: "",
      // 是否显示弹出层
      open: false,
      attrOpen: false,
      codeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
        name: undefined,
        systemName: undefined,
      },
      queryAttrParams: {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
        typeid: undefined,
      },
      // 表单参数
      form: {},
      attrForm: {},
      codeForm: {},
      selectTypeList: [],
      sysModule: [],
      // 表单校验
      rules: {
        moduleName: [
          { required: true, message: "所属模块不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        systemName: [
          { required: true, message: "系统名称不能为空", trigger: "blur" },
        ],
        parentid: [
          { required: true, message: "父类不能为空", trigger: "blur" },
        ],
      },
      attrRules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        plmType: [
          { required: true, message: "PLM类型不能为空", trigger: "blur" },
        ],
        kind: [{ required: true, message: "类型不能为空", trigger: "blur" }],
      },
      codeRules: {},
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_module").then((response) => {
      this.sysModule = this.selectNormalizer(response.data);
    });
  },
  computed: {
    maxHeight() {
      return this.app.screenHeight - 270;
    },
    tableMainWidth() {
      return (
        this.app.screenWidth -
        250 -
        this.tableDependWidth * (this.app.screenWidth - 250)
      );
    },
  },
  methods: {
    /** 查询分类管理列表 */
    getList() {
      this.loading = true;
      listType().then((response) => {
        this.selectTypeList = deepClone(response.rows);
        this.typeList = this.handleTree(response.rows, "id", "parentid");
        this.total = response.total;
        this.tableDependName = response.rows[0].name;
        this.typeID = response.rows[0].id;
        this.queryAttrParams.typeid = response.rows[0].id;
        this.getAttrList();
        this.loading = false;
      });
    },
    getAttrList() {
      this.loading = true;
      listAttr(this.queryAttrParams).then((response) => {
        this.attrList = response.rows;
        this.attrTotal = response.total;
        this.loading = false;
      });
    },
    checkAttr(id, name) {
      this.tableDependName = name;
      this.typeID = id;
      this.queryAttrParams.typeid = id;
      this.getAttrList();
    },
    // 表单取消按钮
    cancel() {
      this.open = false;
      this.codeOpen = false;
      this.attrOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        systemName: undefined,
        status: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleMainSelectionChange(selection) {
      this.mainids = selection.map((item) => item.id);
      this.mainselected = selection;
    },
    // 多选框选中数据
    handleDependSelectionChange(selection) {
      this.dependids = selection.map((item) => item.id);
      this.dependselected = selection;
    },
    /** 新增按钮操作 */
    handleAdd(flag = "") {
      this.reset();
      // this.$set(this.form,'parentid',this.mainids[0])
      if (flag == "super") {
        this.form.parentid = 0;
        this.form.super = true;
      } else {
        this.form.parentid = this.mainids[0];
        this.form.moduleName = this.mainselected[0].moduleName;
      }
      this.open = true;
      this.title = flag == "super" ? "新增超类" : "新增分类";
    },
    /** 新增编码器操作 */
    handleAddCode() {
      this.reset();
      this.codeOpen = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getType(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分类管理";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateType(this.form).then((response) => {
              if (response.code === 200) {
                this.resetForm("attrForm");
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addType(this.form).then((response) => {
              if (response.code === 200) {
                this.resetForm("attrForm");
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除分类管理编号为"' +
          (Array.isArray(ids) && ids.length > 2 ? ids[0] + "等" : ids) +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delType(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    attrDelete(Id) {
      const Ids = Id || this.ids;
      this.$confirm(
        '是否确认删除属性编号为"' +
          (Array.isArray(Ids) && Ids.length > 2 ? Ids[0] + "等" : Ids) +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delAttr(Ids);
        })
        .then(() => {
          this.getAttrList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    addAttr() {
      if (!this.typeID) {
        this.msgError("请选择类型");
        return false;
      }
      this.attrOpen = true;
      this.title = "添加属性列";
    },
    /** 属性提交按钮 */
    submitAttrForm: function () {
      this.$refs["attrForm"].validate((valid) => {
        if (valid) {
          if (this.attrForm.id != undefined) {
            this.attrForm.typeid = this.typeID;
            updateAttr(this.attrForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.attrOpen = false;
                this.getAttrList();
              }
            });
          } else {
            this.attrForm.typeid = this.typeID;
            addAttrForm(this.attrForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.attrOpen = false;
                this.getAttrList();
              }
            });
          }
        }
      });
    },
    /** 属性提交按钮 */
    submitCodeForm: function () {
      this.$refs["codeForm"].validate((valid) => {
        if (valid) {
          this.codeForm.typeid = this.mainids[0];
          // return
          addData("/classify/sequence", this.codeForm).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.codeOpen = false;
            }
          });
        }
      });
    },
    updateSheet() {
      if (!this.typeID) {
        this.msgError("请选择类型");
        return false;
      }
      const tid = this.typeID;
      this.$confirm(
        '是否确认更新编号为"' + tid + '"的数据项到数据表?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateSheet(tid);
        })
        .then(() => {
          this.getAttrList();
          this.msgSuccess("更新成功！");
        })
        .catch(function () {});
    },
    produceCode() {
      if (!this.typeID) {
        this.msgError("请选择类型");
        return false;
      }
      const tid = this.typeID;
      this.$confirm('是否确认生成编号为"' + tid + '"的数据项的代码?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return produceCode(tid);
        })
        .then(() => {
          this.getAttrList();
          this.msgSuccess("更新成功！");
        })
        .catch(function () {});
    },
    tableExtend(type) {
      if (type === 2) {
        if (this.tableDepend === "table-depend") {
          this.tableMainShow = false;
          this.tableDepend = "table-extend";
        } else {
          this.tableMainShow = true;
          this.tableDepend = "table-depend";
        }
      } else {
        if (this.tableMain === "table-main") {
          this.tableDependShow = false;
          this.tableMain = "table-extend";
        } else {
          this.tableDependShow = true;
          this.tableMain = "table-main";
        }
      }
    },
    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel,
        };
      });
      return data;
    },
    // 数据状态字典翻译
    statusFormat(row, column) {
      if (row.status == 1) {
        return "生效";
      } else {
        return "未生效";
      }
    },
  },
};
</script>
